#!/bin/bash

# 查询k8s的Qos资源信息

# 用法说明
if [[ $# -ne 1 ]]; then
  echo "用法: $0 <all|namespace>"
  exit 1
fi

target="$1"
outfile="k8s-deploy-info.csv"

# 表头
echo "NAMESPACE,DEPLOYMENT,CONTAINER,LIMIT_CPU,LIMIT_MEM,REQUEST_CPU,REQUEST_MEM,REPLICAS" > "$outfile"

if [[ "$target" == "all" ]]; then
  deploys=$(kubectl get deployments.apps -A --no-headers | awk '{print $1,$2}')
else
  deploys=$(kubectl get deployments.apps -A --no-headers|grep "$target" | awk '{print $1,$2}')
fi

echo "$deploys" | while read nsname depname; do
  containers=$(kubectl get deployments.apps -n "$nsname" "$depname" -o json | jq -c '.spec.template.spec.containers[]')
  replicas=$(kubectl get deployments.apps -n "$nsname" "$depname" -o json | jq '.spec.replicas // "-"')

  while read -r container; do
    cname=$(echo "$container" | jq -r '.name')
    limit_cpu=$(echo "$container" | jq -r '.resources.limits.cpu // "-"')
    limit_mem=$(echo "$container" | jq -r '.resources.limits.memory // "-"')
    request_cpu=$(echo "$container" | jq -r '.resources.requests.cpu // "-"')
    request_mem=$(echo "$container" | jq -r '.resources.requests.memory // "-"')

    echo "$nsname,$depname,$cname,$limit_cpu,$limit_mem,$request_cpu,$request_mem,$replicas" >> "$outfile"
  done <<< "$containers"
done

echo "结果已输出到 $outfile，可用Excel直接打开。"